package com.xiaoc.bulldozer.facade.impl;

import com.xc.framework.common.exception.BusinessException;
import com.xc.framework.common.utils.BeanUtil;
import com.xc.framework.common.utils.NumberUtil;
import com.xiaoc.bulldozer.common.AccountBalanceConstant;
import com.xiaoc.bulldozer.common.ResponseCode;
import com.xiaoc.bulldozer.common.dto.AccountBalanceDto;
import com.xiaoc.bulldozer.common.model.Account;
import com.xiaoc.bulldozer.common.model.AccountBalance;
import com.xiaoc.bulldozer.common.model.AccountBalanceDetail;
import com.xiaoc.bulldozer.common.model.WeixinUser;
import com.xiaoc.bulldozer.common.service.AccountBalanceDetailService;
import com.xiaoc.bulldozer.common.service.AccountBalanceService;
import com.xiaoc.bulldozer.common.service.AccountService;
import com.xiaoc.bulldozer.common.service.WeixinUserService;
import com.xiaoc.bulldozer.facade.PayFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service("payFacade")
public class PayFacadeImpl implements PayFacade {

    private Logger logger = LoggerFactory.getLogger(PayFacadeImpl.class);

    @Resource(name = "accountService")
    private AccountService accountService;

    @Resource(name = "weixinUserService")
    private WeixinUserService weixinUserService;

    @Resource(name = "accountBalanceService")
    private AccountBalanceService accountBalanceService;

    @Resource(name = "accountBalanceDetailService")
    private AccountBalanceDetailService accountBalanceDetailService;


    @Override
    public WeixinUser getWeixinUserByPhoneNumber(String phoneNumber) {

        Account account = accountService.getAccountByPhoneNumber(phoneNumber);

        if (account == null) {
            logger.error("getWeixinUserByPhoneNumber account is null :phoneNumber = {}", phoneNumber);
            return null;
        }

        WeixinUser weixinUser = weixinUserService.getWeixinUserById(account.getUserId());

        if (weixinUser == null) {
            logger.error("getWeixinUserByPhoneNumber weixinUser is null :phoneNumber = {}", phoneNumber);
            return null;
        }

        return weixinUser;
    }

    @Override
    public Account getAccountByPhoneNumber(String phoneNumber) {
        return accountService.getAccountByPhoneNumber(phoneNumber);
    }

    @Override
    public void updateBalanceByPhoneNumberAndBalanceType(String phoneNumber, Integer balanceType, Integer balance) {

        Account account = accountService.getAccountByPhoneNumber(phoneNumber);

        if (account == null) {
            logger.error("updateBalanceByPhoneNumberAndBalanceType account is null :phoneNumber = {}", phoneNumber);
            throw new BusinessException(ResponseCode.PAY_USER_NOT_EXIST.getCode(), ResponseCode.PAY_USER_NOT_EXIST.getMsg());
        }

        AccountBalance accountBalance = accountBalanceService.getAccountBalanceByUserIdAndType(account.getUserId(), balanceType);

        if (accountBalance == null) {
            logger.error("accountBalance is null, userId={}, balanceType={}", account.getUserId(), balanceType);
            throw new BusinessException(ResponseCode.BUSINESS_ERROR.getCode(), "账户不存在");
        }

        if (accountBalance.getBalance() < balance) {
            logger.error("balance is not enough , phoneNumber={}, userId={}, balance={}, payBalance={}", phoneNumber, account.getUserId(), accountBalance.getBalance(), balance);
            throw new BusinessException(ResponseCode.BUSINESS_ERROR.getCode(), "您的余额不足");
        }


        //更新余额
        long current = System.currentTimeMillis();
        accountBalanceService.updateBalanceAndUpdateTimeById(-balance, current, accountBalance.getId());

        //add accountBalanceDetail
        AccountBalanceDetail accountBalanceDetail = new AccountBalanceDetail();
        accountBalanceDetail.setAccountId(account.getId());
        accountBalanceDetail.setUserId(account.getUserId());
        accountBalanceDetail.setAmount(-balance);
        accountBalanceDetail.setBalanceId(accountBalance.getId());
        accountBalanceDetail.setBalanceType(balanceType);

        //红包提现
        if (AccountBalanceConstant.ACCOUNT_BALANCE_TYPE_MARKET.equals(balanceType)) {
            accountBalanceDetail.setType(AccountBalanceConstant.AccountBalanceDetailConstant.TYPE_AWARD_OUT);
        } else {
            accountBalanceDetail.setType(AccountBalanceConstant.AccountBalanceDetailConstant.TYPE_CASH_OUT);
        }

        accountBalanceDetail.setUpdateTime(current);
        accountBalanceDetail.setCreateTime(current);

        accountBalanceDetailService.save(accountBalanceDetail);

        logger.info("提现用户[[]]提现金额[{}]类型[{}]",account.getId(),balance,balanceType);
    }

    @Override
    public List<AccountBalanceDto> getAccountBalanceDtoListByAccount(Account account) {

        List<AccountBalanceDto> accountBalanceList = new ArrayList<>();

        for (Integer type : AccountBalanceConstant.BALANCE_TYPE_LIST) {

            AccountBalance accountBalance = accountBalanceService.getAccountBalanceAccountIdAndType(account.getId(), type);

            if (accountBalance == null) {
                accountBalance = new AccountBalance();
                accountBalance.setType(type);
                accountBalance.setBalance(0);
            }

            AccountBalanceDto accountBalanceDto = new AccountBalanceDto();
            BeanUtil.copyProperties(accountBalanceDto, accountBalance);

            //红包提现金额 要是3倍数
            if (NumberUtil.equals(type, AccountBalanceConstant.ACCOUNT_BALANCE_TYPE_MARKET)) {
                accountBalanceDto.setPayBalance((accountBalanceDto.getBalance() / AccountBalanceConstant.AWARD_WITHDRAW_MIN) * AccountBalanceConstant.AWARD_WITHDRAW_MIN);
            } else {
                accountBalanceDto.setPayBalance(accountBalance.getBalance());
            }


            accountBalanceList.add(accountBalanceDto);

        }

        return accountBalanceList;
    }
}



